//
//  AddMapViewController.m
//  Xing
//
//  Created by macpro on 16/1/8.
//  Copyright © 2016年 徐番茄丶. All rights reserved.
//

#import "AddMapViewController.h"
#import "MyTools.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "AddMapTableViewCell.h"
@interface AddMapViewController ()<MAMapViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate,MAMapViewDelegate,UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>
@property(nonatomic,strong)CLGeocoder *geocoder;

@end

@implementation AddMapViewController{
    MAMapView *_mapView;
    AMapLocationManager *_locationManager;
    NSMutableArray *_dataarr;
    NSMutableArray *_locationArr;
    UITableView *_tableview;
    MAPointAnnotation *_pointAnnotation;
    BOOL ye;
}
#pragma mark-懒加载
-(CLGeocoder *)geocoder
{
    if (_geocoder==nil) {
        _geocoder=[[CLGeocoder alloc]init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    [self.navigationItem.leftBarButtonItem setTintColor:UIColorFromRGB(0x444444)];
    [self requesttableview];
    [self viewCreate];
   
    ye = NO;
    
}

- (void)viewCreate
{
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, HEIGHT/2+40, WIDTH, HEIGHT/2-100)];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    //
    _locationArr = [[NSMutableArray alloc]init];
    //配置用户Key
    [AMapSearchServices sharedServices].apiKey = @"3c1ed8e77fcfcd1f388026c38564fe01";
    [AMapLocationServices sharedServices].apiKey=@"3c1ed8e77fcfcd1f388026c38564fe01";//定位
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/2+100)];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;//YES 为打开定位，NO为关闭定位
    
    
    [self.view addSubview:_mapView];
    
    _locationManager = [[AMapLocationManager alloc]init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    CLLocationDistance distance=10.0;//十米定位一次
    _locationManager.distanceFilter=distance;
    
    //启动跟踪定位
    [_locationManager startUpdatingLocation];
    _pointAnnotation = [[MAPointAnnotation alloc] init];
}

- (void)requesttableview{
    
    _dataarr = [[NSMutableArray alloc]init];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSString *urlstr = @"http://www.xsy777.com/app/b_send/peilist.html";
    NSDictionary *dic;
    if (![user objectForKey:@"city"]) {
        dic = @{@"address_id":_address_id,
                @"user_token":[user objectForKey:@"token"]};

    }else{
        dic = @{@"address_id":_address_id,
                @"user_token":[user objectForKey:@"token"],
                @"address":[user objectForKey:@"city"]};
    }
    
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"]intValue] == 1) {
            _dataarr = [responseObject objectForKey:@"data"];
            
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        for (NSDictionary *dic in _dataarr) {
             NSArray *array = [[NSString stringWithFormat:@"%@",[dic objectForKey:@"coord"]] componentsSeparatedByString:@"|"];
            [_locationArr addObject:array[0]];

        }
        [self location];
        [_tableview reloadData];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        NSLog(@"=====>%@",error);
    }];
}

- (void)location
{
    MAPointAnnotation *pointAnnotation;
   
    for (int i = 0; i<_locationArr.count; i++) {
         NSArray *array = [[NSString stringWithFormat:@"%@",_locationArr[i]] componentsSeparatedByString:@","];
        CGFloat log=[array[0]floatValue];
        CGFloat lat=[array[1]floatValue];
        pointAnnotation = [[MAPointAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake(lat, log);
        pointAnnotation.title = _dataarr[i][@"nickname"];

        [_mapView addAnnotation:pointAnnotation];
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        annotationView.image = [UIImage imageNamed:@"icon_location"];
        
        return annotationView;
    }
    return nil;
}
#pragma mark - MAMapView 持续定位
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    // NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    if (_pointAnnotation == nil)
    {
        _pointAnnotation = [[MAPointAnnotation alloc] init];
        [_pointAnnotation setCoordinate:location.coordinate];
        
        [_mapView addAnnotation:_pointAnnotation];
    }
    
    [_pointAnnotation setCoordinate:location.coordinate];
    
    [_mapView setCenterCoordinate:location.coordinate];
    [_mapView setZoomLevel:15.1 animated:NO];
    
    
}


#pragma mark - tableView 协议
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataarr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"cell";
    AddMapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[AddMapTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.namelab.text = [NSString stringWithFormat:@"%@",_dataarr[indexPath.row][@"nickname"]];
    NSArray *array = [[NSString stringWithFormat:@"%@",_dataarr[indexPath.row][@"coord"]] componentsSeparatedByString:@"|"];
    cell.address.text = array[1];
    [_locationArr addObject:array[0]];
    cell.otherLab.text = [NSString stringWithFormat:@"%@",_dataarr[indexPath.row][@"gaodejuli"]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *urlstr = @"http://www.xsy777.com/app/b_send/peisonglist.html";
    
    NSDictionary *dic = @{@"pai_uid":_dataarr[indexPath.row][@"uid"],
                @"user_token":[user objectForKey:@"token"],
                @"id":_id};
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//        NSLog(@"%@",[responseObject objectForKey:@"info"]);
        
        [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        
        [_tableview reloadData];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        NSLog(@"=====>%@",error);
    }];
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.translucent = NO;
    self.tabBarController.tabBar.hidden = NO;
}

@end
